package com.jsy.common.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LargeExcelExportExample {
    public static void main(String[] args) {
        // 定义内存中保留的行数，超出此数量的行将被写入磁盘临时文件
        int rowAccessWindowSize = 100;
        // 创建 SXSSFWorkbook 对象
        SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize);
        // 创建工作表
        Sheet sheet = workbook.createSheet("Large Data Sheet");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"序号", "姓名", "年龄"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 模拟大量数据
        int dataSize = 100000;
        List<String[]> data = new ArrayList<>();
        for (int i = 0; i < dataSize; i++) {
            data.add(new String[]{String.valueOf(i + 1), "姓名" + (i + 1), String.valueOf((int) (Math.random() * 100))});
        }

        // 填充数据
        for (int i = 0; i < data.size(); i++) {
            Row row = sheet.createRow(i + 1);
            String[] rowData = data.get(i);
            for (int j = 0; j < rowData.length; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(rowData[j]);
            }
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 写入文件
        try (FileOutputStream fileOut = new FileOutputStream("large_data_export.xlsx")) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放临时文件
            workbook.dispose();
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}